/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年3月7日         Root.Lu
 */

package com.coocaa.app.gamecenter.pages.detail;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

import com.coocaa.app.gamecenter.framework.GameCenterActivity;
import com.coocaa.app.gamecenter.pages.detail.ADView.ADItemData;
import com.coocaa.app.gamecenter.pages.detail.DetailActivity.DetailData.BigPoster;
import com.coocaa.app.gamecenter.pages.detail.DetailView.OnBigPosterClickListener;
import com.coocaa.app.gamecenter.pages.detail.DetailView.SUPPORT_DEVICE;
import com.coocaa.app.gamecenter.pages.detail.DownloadCtrView.DownloadCtrViewListener;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.coocaa.x.service.litepm.aidl.ILitePMInstallListener;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.coocaa.x.service.litepm.data.InstallParams;
import com.coocaa.x.uipackage.widget.SlideFocusView;
import com.skyworth.framework.skysdk.android.SkySystemUtil;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppAdInfo;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.GameDetail;
import com.tianci.appstore.R;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.framework.cache.Cache;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppAction;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.AppDebug;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DetailActivity extends GameCenterActivity implements OnBigPosterClickListener,
        DownloadCtrViewListener {
    public static final String INTENT_APPID_KEY = "com.tianci.gamecenter.DetailActivity.appid";
    public static final String INTENT_PACKAGENAME_KEY = "com.tianci.gamecenter.DetailActivity.pkgname";

    public static class DetailData {
        public static class BigPoster {
            public String small, big;

            public BigPoster(String small, String big) {
                this.small = small;
                this.big = big;
            }
        }

        public String bgURL;
        public String title;
        public List<String> infos;
        public String intro;
        public int device;

        public String posterUrl;
        public String gameVideoUrl = null;

        public List<BigPoster> bigPosterUrls = new ArrayList<BigPoster>();
        public List<ADItemData> ads = new ArrayList<ADView.ADItemData>();
        public String id, packageName;

        public AppStatus status = null;

        public String versionCode;
        public int download_percent = 0;
    }

    private DetailView detailView = null;
    private ADView adView = null;
    private DetailData data = null;
    private static Cache<String, DetailData> appdetailCache = new Cache<String, DetailData>();

    private HashMap<String, DownloadTask> taskMap = new HashMap<String, DownloadTask>();
    private String installing_apk = null;
    private boolean bInstalling = false;

    private SlideFocusView mainView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int width = SkySystemUtil.getDisplayWidth(mContext);
        LogUtils.d("the dpi is " + SkySystemUtil.getDisplayDensity(mContext));
        float div = (float) width / (float) 1920;

        bInstalling = false;
        installing_apk = null;

        super.onCreate(savedInstanceState);
    }
//    @Override
//    protected void onNewIntent(Intent intent)
//    {
//        current = System.currentTimeMillis();
//        final View contentView = createContentView();
//        if (hasCache())
//        {
//            initTitleView();
//            mMainlayout.addView(contentView);
//            updateContentView();
//        } else
//        {
//            new Thread(new Runnable()
//            {
//                @Override
//                public void run()
//                {
//                    try
//                    {
//                        loadData();
//                        runOnUiThread(new Runnable()
//                        {
//                            @Override
//                            public void run()
//                            {
//                                if (current != 0)
//                                {
//                                    initTitleView();
//                                    mMainlayout.addView(contentView);
//                                    updateContentView();
//                                }
//                            }
//                        });
//                    } catch (final Exception e)
//                    {
//                        setLoadDataErrorMsg(e.getMessage());
//                    }
//                }
//            }).start();
//        }
//    }

    @Override
    protected Map<String, String> getPageStartParams() {
        HashMap<String,String> map = new HashMap<String,String>();
        int appId = getIntent().getIntExtra(INTENT_APPID_KEY, -1);
        map.put("app_id", String.valueOf(appId));
        return map;
    }

    @Override
    protected void onDestroy() {
        try {
            XServiceManager.getDownloaderService().clearListener(downloaderStub);
            XServiceManager.getLitePMService().removeInstallListener(installStub);
            installStub = null;
            downloaderStub = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (detailView != null) {
            detailView.destroy();
            detailView.setDownloadCtrViewListener(null);
            detailView.setOnBigPosterClickListener(null);
            detailView = null;
        }
        adView.destroy();
        super.onDestroy();
        adView = null;
        data = null;
        taskMap.clear();
        mainView = null;
//        mMainlayout.removeAllViews();
        // appdetailCache.clear();
    }

    @Override
    public String getName() {
        return "酷游吧详情页";
    }

    @Override
    protected boolean hasCache() {
        return super.hasCache();
    }

    @Override
    protected void loadData() throws Exception {
        // local debug
        // data = new DetailData();
        // data.title = "测试详情";
        // data.bgURL =
        // "http://f.hiphotos.baidu.com/image/pic/item/e1fe9925bc315c60294c22ee8fb1cb13485477d1.jpg";
        // data.posterUrl = "http://img3.imgtn.bdimg.com/it/u=1357150012,3029333703&fm=11&gp=0.jpg";
        // data.dlcount = 8888;
        // data.intro =
        // "一生的爱好起源于少年的经历，习近平也不例外，他对足球的喜爱可以追溯到自己的中学时期。习近平曾就读于北京101中学，在这个足球氛围浓厚的学校，少年时代的习近平便顺理成章地喜爱上了足球。事实上，在上世纪的五、六十年代，不少“红二代”都对足球产生了强烈的兴趣。据新华网报道，那时习近平作为汇文足球队的队员和一些“红二代”学生球员交过手，如101中学校队朱德的孙子和四中校队姬鹏飞的儿子。";
        // if (data.intro.length() > 100)
        // data.intro = data.intro.substring(0, 100) + "...";
        // data.size = 124123213;
        // data.type = "type";
        // data.version = "1.0.0";
        // data.isPosterVideo = true;
        // data.bigPosterUrls.add(new BigPoster(
        // "http://bizhi.zhuoku.com/2009/09/03/manlian/Manchester_united_26.jpg",
        // "http://bizhi.zhuoku.com/2009/09/03/manlian/Manchester_united_26.jpg"));
        // data.bigPosterUrls.add(new BigPoster(
        // "http://asiaballking.com/assets/uploads/editor/images/hunson2.jpg",
        // "http://asiaballking.com/assets/uploads/editor/images/hunson2.jpg"));
        // data.bigPosterUrls.add(new BigPoster(
        // "http://gb.cri.cn/mmsource/images/2014/04/22/32/14743396395251067744.jpg",
        // "http://gb.cri.cn/mmsource/images/2014/04/22/32/14743396395251067744.jpg"));
        //
        // detailView.loadAppInfoBitmap(data.bgURL, data.posterUrl);
        // detailView.loadBigPosterBitmap(data.bigPosterUrls);
        //
        // List<ADItemData> ads = new ArrayList<ADView.ADItemData>();
        //
        // for (int i = 0; i < 5; i++)
        // {
        // ADItemData data = new ADItemData(
        // "http://news.mydrivers.com/img/topimg/20150317/161611834.png", new Intent(""));
        // ads.add(data);
        // }
        // adView.update(ads);

        showloading();
        try {
            Intent intent = getIntent();
            Uri uri = intent.getData();
            if (uri != null) {
                String packageName = uri.getQueryParameter("id");// "com.bf.FeiXingQi_TV";
                if (!(packageName == null || packageName.equals(""))) {
                    data = getAppDetail(-1, packageName, "");
                } else {
                    String skyid = uri.getQueryParameter("skyid");
                    data = getAppDetail(Integer.valueOf(skyid), packageName, "");
                }
            } else {
                String appid = intent.getStringExtra(INTENT_APPID_KEY);
                if (appid == null) {
                    int _appid = intent.getIntExtra(INTENT_APPID_KEY, -1);
                    if (_appid != -1)
                        appid = String.valueOf(_appid);
                }
                if (appid != null) {
                    data = getAppDetail(Integer.valueOf(appid), null, "");
                } else {
                    String packageName = intent.getStringExtra(INTENT_PACKAGENAME_KEY);
                    if (!(packageName == null || packageName.equals("")))
                        data = getAppDetail(Integer.valueOf(appid), packageName, "");
                }
//
//                try {
//                    String appid = intent.getStringExtra(INTENT_APPID_KEY);
//                    if (appid != null)
//                        data = getAppDetail(Integer.valueOf(appid), null, "");
//                    else {
//                        String packageName = intent.getStringExtra(INTENT_PACKAGENAME_KEY);
//
//                        if (!(packageName == null || packageName.equals("")))
//                            data = getAppDetail(Integer.valueOf(appid), packageName, "");
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    int appid = intent.getIntExtra(INTENT_APPID_KEY, -1);
//                    if (appid != -1)
//                        data = getAppDetail(appid, null, "");
//                    else {
//                        String packageName = intent.getStringExtra(INTENT_PACKAGENAME_KEY);
//
//                        if (!(packageName == null || packageName.equals("")))
//                            data = getAppDetail(Integer.valueOf(appid), packageName, "");
//                    }
//                }
            }
            if (data == null)
                throw new Exception(mContext.getResources().getString(R.string.detail_failed_tip));// handle
                // loading
                // error!
            else {
                XServiceManager.getDownloaderService().clearListener(downloaderStub);
                XServiceManager.getLitePMService().removeInstallListener(installStub);
                XServiceManager.getDownloaderService().setListener(downloaderStub);
                XServiceManager.getLitePMService().addInstallListener(installStub);
                List<DownloadTask> list = XServiceManager.getDownloaderService().getTaskList();
                synchronized (taskMap) {
                    taskMap.clear();
                    for (DownloadTask task : list)
                        taskMap.put(task.ID, task);
                }
            }
            // String string = "scheme:" + uri.getScheme() + " host:" + uri.getHost() + " path:"
            // + uri.getPath() + " auth:" + uri.getAuthority() + " query:" + uri.getQuery()
            // + " frag:" + uri.getFragment() + " pkg:" + pkg;
        } catch (Exception e) {
            throw new Exception(mContext.getResources().getString(R.string.gc_detail_load_error));
        } finally {
            hideloading();
        }
        // Intent intent = getIntent();
        // if (intent != null)
        // {
        // int id = intent.getIntExtra(INTENT_DETAIL_ID_KEY, -1);
        // if (id != -1)
        // {
        //
        // } else
        // {
        // String packageName = intent.getStringExtra(INTENT_DETAIL_PACKAGENAME_KEY);
        // if (packageName == null || packageName.equals(""))
        // {
        // }
        // }
        // }

        // XServiceManager.getDownloaderService().setListener(downloaderStub);
        // XServiceManager.getLitePMService().setPMListener(appPMStub);
        // List<DownloadTask> list = XServiceManager.getDownloaderService().getTaskList();
        // synchronized (taskMap)
        // {
        // taskMap.clear();
        // for (DownloadTask task : list)
        // taskMap.put(task.ID, task);
        // }
        // data = getAppDetail(Integer.valueOf(id), "", "");
    }

    private DetailData toDetailData(GameDetail detailData) {
        DetailData ret = new DetailData();
        ret.id = detailData.details.id;
        ret.packageName = detailData.details.packageName;
        ret.versionCode = detailData.details.versionCode;
        ret.title = detailData.details.title;
        ret.bgURL = detailData.bigIcon;//
        LogUtils.d("PP", "toDetailData bg_URL:" + ret.bgURL);
        // detailData.details.
        ret.posterUrl = detailData.details.iconUrl;// detailData.details.iconUrl;
        ret.infos = detailData.details.infoList;
        ret.device = toDevices(detailData.details.infoList);
        for (String info : ret.infos) {
            if (info.contains("支持"))// fucking this method!!!!!
                ret.infos.remove(info);
        }
        ret.intro = detailData.details.introduction;
        ret.intro = ret.intro.replace('\n', ' ');
        ret.intro = ret.intro.replace('\r', ' ');
        if (ret.intro.length() > 100)
            ret.intro = ret.intro.substring(0, 100) + "...";
        ret.gameVideoUrl = detailData.game_movie_url;
        int sssize = detailData.details.screenShotsPreview.size();
        for (int i = 0; i < sssize; i++) {
            ret.bigPosterUrls.add(new BigPoster(detailData.details.screenShotsPreview.get(i),
                    detailData.details.screenShotsBig.get(i)));
        }

        for (int i = 0; i < detailData.game_ad.size(); i++) {
            AppAdInfo adInfo = detailData.game_ad.get(i);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            try {
                intent.setData(Uri.parse(adInfo.linkUrl));
            } catch (Exception e) {
            }
            ADItemData data = new ADItemData(adInfo.smallPicUrl, intent);
            ret.ads.add(data);
        }
        return ret;
    }

    private int toDevices(List<String> infos) {
        int device = 0;
        if (infos != null && infos.size() > 0) {
            for (int i = 0; i < infos.size(); i++) {
                if (infos.get(i).contains(SkyConstants.HAND_SHANK)) {
                    device |= SUPPORT_DEVICE.JOYSTICK.flag;
                }
                if (infos.get(i).contains(SkyConstants.MOUSE)) {
                    device |= SUPPORT_DEVICE.MOUSE.flag;
                }
                if (infos.get(i).contains(SkyConstants.REMOTE_CONTROL)) {
                    device |= SUPPORT_DEVICE.REMOTE.flag;
                }
                if (infos.get(i).contains(SkyConstants.CONTROL_LEAP_MOTION)) {
                    device |= SUPPORT_DEVICE.CONTROL_LEAP_MOTION.flag;
                }
                if (infos.get(i).contains(SkyConstants.INDUCTION_LEAP_MOTION)) {
                    device |= SUPPORT_DEVICE.INDUCTION_LEAP_MOTION.flag;
                }
                if (infos.get(i).contains(SkyConstants.MOBLIE)) {
                    device |= SUPPORT_DEVICE.MOBLIE.flag;
                }
                if (infos.get(i).contains(SkyConstants.GUN)) {
                    device |= SUPPORT_DEVICE.GUN.flag;
                }
            }
        }
        return device;
    }

    private DetailData getAppDetail(int appid, String packageName, String version) {
        DetailData app = null;
        if (appid != -1)
            app = appdetailCache.get(String.valueOf(appid));
        else
            app = appdetailCache.get(packageName);
        try {
            if (app == null) {
                if (appid != -1) {
                    GameDetail detailData = CoocaaApplication.getCoocaaWebService()
                            .getAppStoreService().getGameDetail(null, String.valueOf(appid));
                    app = toDetailData(detailData);
                    appdetailCache.add(String.valueOf(appid), app);
                } else {
                    GameDetail detailData = CoocaaApplication.getCoocaaWebService()
                            .getAppStoreService().getGameDetail(packageName, null);
                    app = toDetailData(detailData);
                    appdetailCache.add(packageName, app);
                }
            }

            if (app != null) {
                app.status = AppDataProvider.getInstance().getAppStatus(app.packageName,
                        app.versionCode);
                String downurl = getDownurl(app.id, "");
                DownloadTask task = taskMap.get(downurl);
                if (task != null) {
                    try {
                        DownloadTask _task = XServiceManager.getDownloaderService().refresh(task);
                        if (_task.info.length > 0) {
                            app.download_percent = (int) (_task.info.current * 100 / _task.info.length);
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } catch (AppStoreException e) {
            LogAPIForAppStore
                    .reportInterfaceError("游戏中心通过包名或ID获取游戏详情", Android.throwable2String(e));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    TipToast.getInstance(mContext).showTipToast("获取后台数据超时！");
                }
            });
            e.printStackTrace();
        }
        return app;
    }

    @Override
    protected void updateContentView() {
        detailView.loadAppInfoBitmap(data.bgURL, data.posterUrl);
        detailView.loadBigPosterBitmap(data.bigPosterUrls);
        adView.update(data.ads);
        mainView.initChildView(detailView);
        mainView.initChildView(adView);
        detailView.setDownloadCtrViewListener(this);
        detailView.setOnBigPosterClickListener(this);
        detailView.updateAppInfo(data.title, data.packageName, data.gameVideoUrl, data.infos, data.device, data.intro);
        detailView.updateStatus(data.status, data);
        detailView.updateDownloadPercent(data.download_percent);
        detailView.setFocus();
        updateTitle(data.title);
        mainView.showFocusView();
    }

    @Override
    public void onBigPosterClick(BigPoster url) {
    }

    @Override
    protected View createContentView() {
        if (detailView != null) {
            detailView.destroy();
            detailView.setDownloadCtrViewListener(null);
            detailView.setOnBigPosterClickListener(null);
            detailView = null;
        }
        if (adView != null) {
            adView.destroy();
            adView = null;
        }


        detailView = new DetailView(mContext);
        mainView = new SlideFocusView(mContext, R.drawable.game_center_focus);
        mainView.hideFocusView();
        mainView.addView(detailView);
        adView = new ADView(mContext);
        detailView.updateAD(adView);
        return mainView;
    }

    private ILitePMInstallListener.Stub installStub = new ILitePMInstallListener.Stub() {
        @Override
        public void onInstallStart(String apkfile, AppInfo appInfo, final InstallParams params) throws RemoteException {
            if (appInfo.pkgName.equals(data.packageName)) {
                bInstalling = true;
                if (CoocaaApplication.isRoot()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (detailView != null)
                                detailView.updateStatus(AppStatus.INSTALLING, data);
                        }
                    });
                }
            }
        }

        @Override
        public void onInstallEnd(String apkfile, AppInfo appInfo, int success, String extra, final InstallParams params)
                throws RemoteException {
            AppDebug.debug("onInstallEnd:" + installing_apk + "  success:" + success);
            if (installing_apk != null && installing_apk.equals(apkfile)) {
                bInstalling = false;
                if (success == 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (detailView != null)
                                detailView.updateStatus(AppStatus.INSTALLED, data);
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (detailView != null)
                                detailView.updateStatus(AppStatus.DOWNLOADED, data);
                        }
                    });
                }
            }
        }
    };

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {

        @Override
        public void onReady(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onReady " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            if (task.ID.equals(currentUrl)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateStatus(AppStatus.WAITING, data);
                    }
                });
            }
        }

        @Override
        public void onPrepare(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStart(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onStart " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            if (task.ID.equals(currentUrl)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateStatus(AppStatus.DOWNLOADING, data);
                    }
                });
            }
        }

        @Override
        public void onStop(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onStop " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            if (task.ID.equals(currentUrl)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateStatus(AppStatus.DOWNLOAD_PAUSED, data);
                    }
                });
            }
        }

        @Override
        public void onFinish(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onFinish " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            if (task.ID.equals(currentUrl)) {
                installing_apk = task.savepath + task.filename;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateStatus(AppStatus.DOWNLOADED, data);
                    }
                });
            }
        }

        @Override
        public void onDelete(final DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onDelete " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            synchronized (taskMap) {
                taskMap.remove(currentUrl);
            }
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            if (task.ID.equals(currentUrl) && !bInstalling) {
                try {
                    if (XServiceManager.getLitePMService().isInstalled(extra.pkgname)) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                if (detailView != null)
                                    detailView.updateStatus(AppStatus.INSTALLED, data);
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                if (detailView != null)
                                    detailView.updateStatus(AppStatus.NOT_DOWNLOADED, data);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onProcessInfo(final DownloadTask task, final ProcessInfo info)
                throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("onProcessInfo:" + info + "  task.ID.equals(id):"
                    + task.ID.equals(currentUrl) + "  bInstalling:" + bInstalling);
            if (task.ID.equals(currentUrl) && !bInstalling) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateDownloadPercent(info.percent);
                    }
                });
            }
        }

        @Override
        public void onError(final DownloadTask task, final DownloadError error)
                throws RemoteException {
            // TODO Auto-generated method stub
            AppDebug.debug("AppStoreDetailPageController onError " + "task.ID.equals(id):"
                    + task.ID.equals(currentUrl));
            if (task.ID.equals(currentUrl)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (detailView != null)
                            detailView.updateStatus(AppStatus.DOWNLOAD_PAUSED, data);
                        // downloadListener.onUpdateStatus(task.task.id, AppStatus.NOT_DOWNLOADED);
                        LogUtils.d("PP", "onError:" + error.toString());
                    }
                });
            }
        }
    };

    private String currentUrl = null;
    private static Map<String, String> urlMap = new HashMap<String, String>();

    private String getDownurl(String appid, String usercount) {
        try {
            String downurl = null;
            synchronized (urlMap) {
                downurl = urlMap.get(appid);
            }
            if (downurl == null) {
                downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                        Integer.valueOf(appid), usercount);
                urlMap.put(appid, downurl);
            }
            System.out.println("download url:" + downurl);
            currentUrl = downurl;
            return downurl;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取应用下载地址接口",
                    Android.throwable2String(e));
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onAction(AppAction action, Object obj) {
        try {
            String appid = data.id;
            String download_url = null;
            while (download_url == null)
                download_url = getDownurl(appid, "");
            switch (action) {
                case ACTION_UPGRADE: // 升级
                    // logSent = true;
                case ACTION_DOWNLOAD: // 下载
                    if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
                        break;
                    LogUtils.d("download_url:" + download_url);
                    if (download_url != null) {
                        try {
                            DownloadTask task = taskMap.get(appid);

                            if (task == null) {
                                DownloadExtra extra = new DownloadExtra(data.id, data.packageName,
                                        data.posterUrl, data.title);
                                task = new DownloadTask(download_url);
                                task.title = data.title;
                                task.url = download_url;
                                task.filename = data.packageName + ".apk";
                                task.extra = extra.toString();
                                synchronized (taskMap) {
                                    taskMap.put(download_url, task);
                                }
                                // if (!logSent)
                                // sendBtnClickLOG("下载", Integer.valueOf(extra.appid), extra.title);//
                                // getString(R.string.detail_download));
                                // else
                                // sendBtnClickLOG("升级", Integer.valueOf(extra.appid), extra.title);//
                                // getString(R.string.detail_upgrade));
                            }
                            XServiceManager.getDownloaderService().add(task);
                            XServiceManager.getDownloaderService().start(task);
                            task = XServiceManager.getDownloaderService().refresh(task);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (detailView != null)
                                        detailView.updateStatus(AppStatus.WAITING, data);
                                }
                            });
                        } catch (RemoteException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    break;
                case ACTION_PAUSE: // 暂停
                    try {
                        DownloadTask task = null;
                        synchronized (taskMap) {
                            task = taskMap.get(download_url);
                        }
                        if (task != null) {
                            // AppDataProvider.getInstance().getServiceData().stop(task);
                            XServiceManager.getDownloaderService().stop(task);
                            DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                    DownloadExtra.class);
                            // sendBtnClickLOG("暂停", Integer.valueOf(extra.appid), extra.title);//
                            // getString(R.string.detail_pause));
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_CONTINUE: // 继续下载
                    try {
                        DownloadTask task = null;
                        synchronized (taskMap) {
                            task = taskMap.get(download_url);
                        }
                        if (task != null) {
                            if (task.url == null) {
                                while (task.url == null)
                                    task.url = getDownurl(appid, "");
                            }
                            XServiceManager.getDownloaderService().start(task);
                            // AppDataProvider.getInstance().getServiceData().start(task);
                            DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                    DownloadExtra.class);
                            // sendBtnClickLOG("继续下载", Integer.valueOf(extra.appid), extra.title);//
                            // getString(R.string.detail_contiue_download));

                            final DownloadTask _task = task;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    detailView.updateStatus(AppStatus.WAITING, data);
                                    // downloadListener.onUpdateStatus(_task.ID, AppStatus.WAITING);
                                }
                            });
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_INSTALL: // 安装
                    try {
                        DownloadTask task = null;
                        synchronized (taskMap) {
                            task = taskMap.get(download_url);
                        }
                        if (task != null) {
                            installing_apk = task.savepath + task.filename;
                            InstallParams params = new InstallParams();
                            params.setFrom(InstallParams.INSTALL_FROM.COOCAA_MARKET);
                            XServiceManager.getLitePMService().install(installing_apk, CoocaaApplication.isRoot(), params);
                            DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                    DownloadExtra.class);
                            // sendBtnClickLOG("安装", Integer.valueOf(extra.appid), extra.title);//
                            // getString(R.string.detail_install));
                            //同应用圈详情页，若是静默安装，则不用强制刷新状态
//                            if (CoocaaApplication.isRoot()) {
//                                runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        // TODO Auto-generated method stub
//                                        detailView.updateStatus(AppStatus.INSTALLING, data);
//                                        // downloadListener.onUpdateStatus(id, AppStatus.INSTALLING);
//                                    }
//                                });
//                            }
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_CANCEL: // 取消
                    // logSent = true;
                case ACTION_DELETE: // 删除
                    try {
                        DownloadTask task = null;
                        synchronized (taskMap) {
                            task = taskMap.get(download_url);
                        }
                        if (task != null) {
                            XServiceManager.getDownloaderService().delete(task);
                            DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                                    DownloadExtra.class);
                            // if (logSent)
                            // sendBtnClickLOG("取消", Integer.valueOf(extra.appid), extra.title); //
                            // sendBtnClickLOG(getString(R.string.detail_cancle));
                            // else
                            // sendBtnClickLOG("删除", Integer.valueOf(extra.appid), extra.title);//
                            // getString(R.string.detail_install));
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_UNINSTALL: // 卸载
                    try {
                        XServiceManager.getLitePMService().uninstall(data.packageName,
                                CoocaaApplication.isRoot());
                        // sendBtnClickLOG("卸载", -1, pkg);// getString(R.string.detail_uninstall));
                        if (CoocaaApplication.isRoot()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    detailView.updateStatus(AppStatus.UNINSTALLING, data);
                                    // downloadListener.onUpdateStatus(id, AppStatus.UNINSTALLING);
                                }
                            });
                        }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_LAUNCH: // 打开
                    try {
                        XServiceManager.getLitePMService().startApp(mContext.getClass().getName(), false, data.packageName);
                        // List<AppInfo> list = XServiceManager.getLitePMService().getInstalledApps();
                        // for (AppInfo app : list)
                        // {
                        // if (app.pkgName.equals(data.packageName))
                        // {
                        // XServiceManager.getLitePMService().startApp(data.packageName);
                        // // sendBtnClickLOG("打开", -1, pkg);// getString(R.string.app_open));
                        // break;
                        // }
                        // }
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ACTION_NULL: // 不做任何操作
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
